
import React, { useState, useEffect } from 'react';
import axios from '../../API'; // 自定义的 axios 实例
import '../../style/zhanghu.css';

const ProfileModal = ({ onClose, isVisible, userId, userNickname, onAvatarUpdate }) => {
  const [isEditing, setIsEditing] = useState(false);
  const [avatar, setAvatar] = useState('src/img/avatar.jpg');
  const [nickname, setNickname] = useState(userNickname);
  const [gender, setGender] = useState('');
  const [signature, setSignature] = useState('');
  const [birthday, setBirthday] = useState('');

  const getAvatarUrl = (avatar) => {
    if (!avatar) {
      return 'src/img/avatar.jpg'; // 默认头像路径
    }
    const timestamp = new Date().getTime(); // 强制清除缓存
    if (avatar.startsWith('http')) {
      return `${avatar}?t=${timestamp}`;
    }
    if (avatar.startsWith('/uploads')) {
      return `http://localhost:8088${avatar}?t=${timestamp}`;
    }
    return `http://localhost:8088/uploads/avatars/${avatar}?t=${timestamp}`;
  };

  const handleAvatarChange = (e) => {
    const file = e.target.files[0];
    if (!file) return;

    if (!file.type.startsWith('image/')) {
      alert('请选择有效的图片文件！');
      return;
    }

    if (file.size > 5 * 1024 * 1024) {
      alert('图片大小不能超过5MB！');
      return;
    }


    const formData = new FormData();
    formData.append("file", file);

    axios.post(`/api/user/info/uploadAvatar/${userId}`, formData, {
      headers: { "Content-Type": "multipart/form-data" },
    })
      .then(response => {
        const uploadedUrl = response.data.data.url;
        // 打印出后端返回的头像 URL
        console.log('上传成功！头像 URL:', uploadedUrl);

        // 强制清除缓存
        const updatedAvatar = `${uploadedUrl}?t=${new Date().getTime()}`;
        setAvatar(updatedAvatar);

        // 可选：刷新用户数据
        axios.get(`/api/user/info/${userId}`)
          .then(userResponse => {
            const userInfo = userResponse.data.data;
            setAvatar(getAvatarUrl(userInfo.avatar));
          })
          .catch(err => {
            console.error("获取用户信息失败：", err);
          });

        // 更新父组件的状态
        onAvatarUpdate(updatedAvatar, nickname);

        alert("头像上传成功！");
      })
      .catch(error => {
        console.error("上传头像失败：", error);
        alert("头像上传失败，请稍后重试！");
      });
  };

  const handleSave = () => {
    const updatedInfo = {
      infoId: userId,
      nickname,
      gender,
      signature,
      birthday,
      avatar, // 确保传递头像 URL
    };

    axios.put(`/api/user/info/${userId}`, updatedInfo)
      .then(response => {
        alert('个人信息更新成功！');
        onAvatarUpdate(avatar, nickname); // 更新父组件的头像
        setIsEditing(false);
      })
      .catch(error => {
        alert('更新失败，请稍后重试！');
        console.error('Error updating user info:', error);
      });
  };

  useEffect(() => {
    if (userId && isVisible) {
      axios.get(`/api/user/info/${userId}`)
        .then(response => {
          const userInfo = response.data.data;
          console.log("Fetched User Info:", userInfo);
          const fullAvatarUrl = getAvatarUrl(userInfo.avatar);
          setAvatar(fullAvatarUrl);
          setNickname(userInfo.nickname);
          setGender(userInfo.gender);
          setSignature(userInfo.signature);
          setBirthday(userInfo.birthday);
        })
        .catch(error => {
          console.error("Error fetching user info:", error);
        });
    }
  }, [userId, isVisible]);

  const handleEdit = () => {
    setIsEditing(true);
  };

  const handleCancel = () => {
    setIsEditing(false);
  };

  return (
    <div
      className={`profile-modal-overlay ${isVisible ? 'profile-modal-show' : ''}`}
      onClick={onClose}
    >
      <div className="profile-modal" onClick={(e) => e.stopPropagation()}>
        {isEditing ? (
          <>
            <img
              src={avatar}
              alt="avatar"
              className="profile-avatar"
              onClick={() => document.getElementById('avatarInput').click()}
              onError={(e) => {
                e.target.onerror = null; // 防止无限触发
                e.target.src = '/img/avatar.jpg'; // 加载失败时使用默认头像
              }}
              style={{ cursor: 'pointer' }}
            />
            <input
              type="file"
              id="avatarInput"
              accept="image/*"
              onChange={handleAvatarChange}
              style={{ display: 'none' }}
            />
            <input
              type="text"
              value={nickname}
              onChange={(e) => setNickname(e.target.value)}
              className="profile-input"
              placeholder="昵称"
            />
            <select
              value={gender}
              onChange={(e) => setGender(e.target.value)}
              className="profile-input"
            >
              <option value="男">男</option>
              <option value="女">女</option>
              <option value="未知">未知</option>
            </select>
            <input
              type="text"
              value={signature}
              onChange={(e) => setSignature(e.target.value)}
              className="profile-input"
              placeholder="个性签名"
            />
            <input
              type="date"
              value={birthday}
              onChange={(e) => setBirthday(e.target.value)}
              className="profile-input"
              placeholder="生日"
            />
            <div className="profile-btn-group">
              <button className="profile-btn" onClick={handleSave}>
                保存
              </button>
              <button className="profile-btn" onClick={handleCancel}>
                取消
              </button>
            </div>
          </>
        ) : (
          <>
            <img src={avatar} alt="avatar" className="profile-avatar" />
            <p className="profile-text">昵称：{nickname}</p>
            <p className="profile-text">性别：{gender}</p>
            <p className="profile-text">个性签名：{signature}</p>
            <p className="profile-text">生日：{birthday}</p>
            <button className="profile-btn" onClick={handleEdit}>
              编辑个人信息
            </button>
          </>
        )}
      </div>
    </div>
  );
};

export default ProfileModal;


